import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin';
import { Park } from './park';
import { UserSettingProvider } from '../user-setting/user-setting';
import { SqliteHelperProvider } from '../sqlite-helper/sqlite-helper';

/*
  Generated class for the ParkDataProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class ParkDataProvider {
  private readonly baseUrl:string ='https://api2.bmob.cn/1/';
  private readonly httpHeaders:HttpHeaders=new HttpHeaders({
    'X-Bmob-Application-Id':'f68b5d0362c7c0522693b9685d255d9a',
    'X-Bmob-REST-API-Key':'0d3668e8eaeacc9de420e64b4f5415d7',
    'Content-Type':'application/json'
  });
  constructor(public http: HttpClient,
    private userSettingProvider:UserSettingProvider,
    private sqliteHelperProvider:SqliteHelperProvider) {
   
  }
  /**
   * 分页获取景区数据
   * @param num 
   * @param page 
   */
  getParks(num:number,page:number):Observable<Park[]>{
    let _params=new HttpParams()
    .set('limit',`${num}`)
    .set('skip',`${(page-1)*num}`);
    return this.http.get<Park[]>(`${this.baseUrl}classes/park`,
    {headers:this.httpHeaders,params:_params}).map(_=>_['results']);
  }
/**
 * 获取记录条数
 */
  getCount():Observable<number>{
    return this.http.get<number>(`${this.baseUrl}classes/park?limit=0&count=1`, {headers:this.httpHeaders}).map(data=>data['count']);
  }

  getPark(objectId:string):Observable<Park>{
    return this.http.get<Park>(`${this.baseUrl}classes/park/${objectId}`, {headers:this.httpHeaders});
  }
/**
 * 获取所有记录
 * @param total 
 */
  getAllParks(total:number):Observable<Park[][]>{
    let num=250;
    let all:Observable<Park[]>[]=[];
    for(let index=0;index<=total/num;index++){
      let _params=new HttpParams()
    .set('limit',`${num}`)
    .set('skip',`${index*num}`);
    all[index]=this.http.get<Park[]>(`${this.baseUrl}classes/park`,
    {headers:this.httpHeaders,params:_params}).map(_=>_['results']);
    }
    return Observable.forkJoin(all);
  }

  /**
   * 获取搜索记录集
   * @param searchParks 
   */
  getSearchParks(searchParks:Park[]):Observable<Park[]>{
    let all:Observable<Park>[]=[];
    for(let i=0;i<searchParks.length;i++){
      all[i]=this.http.get<Park>(`${this.baseUrl}classes/park/${searchParks[i].objectId}`, {headers:this.httpHeaders});
    }
    return Observable.forkJoin(all);
  }

  setParksToCache(forceRefresh:boolean=false):Promise<any>{
    return new Promise<any>((resolve,reject)=>{
      this.userSettingProvider.isRefreshData()
      .then(isRefresh=>{
        console.log(`是否刷新：${isRefresh}`);
        console.log(`是否强制刷新：${forceRefresh}`);
        if(forceRefresh || isRefresh){
          this.sqliteHelperProvider.createOrOpenDb()//打开新建数据库
          .then(()=>{
            return this.sqliteHelperProvider.executeSql('DELETE FROM parks_lite',[]);//清空缓存
          })
          .then(()=>{
            return this.getCount().toPromise();//获取远端数据记录数
          })
          .then(total=>{
            return this.getAllParks(total).toPromise();//获取远端数据
          })
          .then(data=>{
            data.forEach(parks=>{
              console.log(`待加入数据：${parks.length}`);
              let sql='INSERT INTO parks_lite (objectId,name,point)';
              sql+=` SELECT '${parks[0].objectId}','${parks[0].name}','${parks[0].point}'`;
              for(let i=1;i<parks.length;i++){
                sql+=` UNION ALL SELECT '${parks[i].objectId}','${parks[i].name}','${parks[i].point}'`
              }
              this.sqliteHelperProvider.executeSql(sql,[]);
            });//插入数据到数据库
            // data.forEach(parks => {
            //   parks.forEach(park=>{
            //     let sql='insert INTO parks_lite (obejectId,name,point) VALUES(?,?,?)';
            //     let sql_params=[park.objectIde,park.name,park.point];
            //     this.sqliteHelperProvider.executeSql(sql,sql_params);
            //   });
            // });
          })
          .then(()=>{
            this.userSettingProvider.setRefreshData();
          })
          .catch(err=>{
            console.log(err);
            reject(err);
          });
        }
      });
    });
  }

/**
 * 从缓存中读取数据
 */
  getParksFromCache():Promise<any>{
    return this.sqliteHelperProvider.createOrOpenDb().then(()=>{
      return this.sqliteHelperProvider.executeSql('SELECT * FROM parks_lite',[]);
    });

  }
  /**
   * 获取缓存记录数
   */
  getCacheCount():Promise<any>{
    return this.sqliteHelperProvider.createOrOpenDb().then(()=>{
      return this.sqliteHelperProvider.executeSql('SELECT COUNT(1) AS count FROM parks_lite',[]);
    });
  }
}
